package com.tarena.lbs.coupon.dao.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.tarena.lbs.coupon.dao.mapper.StockMapper;
import com.tarena.lbs.coupon.dao.repository.StockRepository;
import com.tarena.lbs.coupon.pojo.po.CouponStockPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * @className: CouponStockRepositoryImpl
 * @author: Feng-hongliang
 * @date: 2025/10/11 15:23
 * @Version: 1.0
 * @description:
 */
@Slf4j
@Repository("stockRepository")
public class CouponStockRepositoryImpl implements StockRepository {
    @Autowired
    private StockMapper stockMapper;

    @Override
    public int insert(CouponStockPO couponStockPO) {
        try {
            int result = stockMapper.insert(couponStockPO);
            if (result != 1) {
                log.warn("优惠券库存插入记录数异常，预期1条，实际{}条，couponId={}",
                        result, couponStockPO.getCouponId());
            }
            return result;
        } catch (Exception e) {
            log.error("插入优惠券库存失败，couponId={}, businessId={}",
                    couponStockPO.getCouponId(), couponStockPO.getBusinessId(), e);
            throw new RuntimeException("插入优惠券库存失败", e);
        }
    }

    public CouponStockPO findByCouponId(Integer couponId) {
        // 创建查询条件构造器
        QueryWrapper<CouponStockPO> queryWrapper = new QueryWrapper<>();
        // 设置查询条件为 coupon_id = couponId
        queryWrapper.eq("coupon_id", couponId);
        // 调用 mapper 的 selectOne 方法获取单个结果
        return stockMapper.selectOne(queryWrapper);
    }

    @Override
    public int deductStock(Integer couponId) {
        int result = stockMapper.update(null,
                new LambdaUpdateWrapper<CouponStockPO>()
                        .eq(CouponStockPO::getCouponId, couponId)
                        .gt(CouponStockPO::getNum, 0)
                        .setSql("num = num - 1")
        );

        if (result != 1) {
            log.warn("优惠券库存扣减失败，couponId={}, 影响行数: {}", couponId, result);
            throw new RuntimeException("优惠券库存不足，couponId=" + couponId);
        }

        log.info("优惠券库存扣减成功，couponId={}", couponId);
        return result;
    }

    @Override
    public int decreaseStock(Integer couponId, Integer count) {
        throw new UnsupportedOperationException("暂不支持该功能");
    }

}
